<?php

namespace App\Http\Controllers\Tools;

use App\Http\Common\DayTimes;
use App\Http\Common\MyUtils;
use App\Http\Common\WeChatApp;
use App\Http\Controllers\BaseController;
use App\Models\AreaApp;
use App\Models\ChargeBills;
use App\Models\Csyys\BaseOtherSetting;
use App\Models\Csyys\Order;
use App\Models\Csyys\RepairBills;
use App\Models\Csyys\WeChat;
use App\Models\Front\Bill;
use App\Models\Houswholds;
use App\Models\My\User;
use App\Models\WyBill;
use EasyWeChat\Factory;
use Exception;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class WeChatController extends BaseController
{
    public $instance = null;//  物业的 实例化
    public $requestOthers = "";// 其他参数
    public function __construct()
    {
        parent::__construct();
        $this->instance = WeChatApp::getPublicInstance();
        $this->model = new WeChat();
        $this->getConfig();
    }

    /**
     * 拿到腾讯传递来的配置
     * 版本2 实现能够 识别当前是 物业缴费 还是运营商缴费，如果是物业缴费的 就交到物业的商户号里面
     * @return void
     */
    public function getConfig(){
        try{
            //接收传送的数据
            $fileContent = file_get_contents("php://input");
            $this->requestOthers = $this->request;
            $this->request = simplexml_load_string($fileContent, 'SimpleXMLElement', LIBXML_NOCDATA);
            $baseOtherSetting = BaseOtherSetting::where('WECHAT_APP_APPID',(string)$this->request->appid)
                ->where('WECHAT_PAYMENT_MCH_ID',(string)$this->request->mch_id)
                ->get('*')
                ->first();
            $this->instance->setBaseConfig($baseOtherSetting);
        }catch (Exception $e){
        }
    }
    /**
     * 商家提现 成功 的 回调接口 会得到接口参数 为 class = "";
     * request 为 FormRequest
     */
    public function contractNotifyCommon(){
        $class = (string)$this->request->attach;
        $app = Factory::payment($this->instance->config);
        $response = $app->handlePaidNotify(function ($message, $fail) use($app,$class){
            try{
                // 使用通知里的 "微信支付订单号" 或者 "商户订单号" 去自己的数据库找到订单
                $orders = $class::where('common_order_number',$message['out_trade_no'])->get()->all();
                foreach ($orders as $v){
                    if ($v->if_payment===1) { // 如果订单不存在 或者 订单已经支付过了
                        return true; // 告诉微信，我已经处理完了，订单没找到，别再通知我了
                    }
                }
                $weChatOrder = $app->order->queryByOutTradeNumber($message['out_trade_no']);
                if (!$weChatOrder) {// 查询到了该条订单
                    return false;
                }
                if(MyUtils::sg($weChatOrder,'return_code') !== 'SUCCESS') {// 表示该条订单支付成功
                    return false;
                }
                if (MyUtils::sg($message, 'result_code') !== 'SUCCESS') {// 用户是否支付成功
                    return false;
                }
                if (MyUtils::sg($message, 'result_code') === 'FAIL') {// 失败
                    return false;
                }
                if (MyUtils::sg($message, 'result_code') === 'CANCEL') {// 取消
                    $temp = true;
                    foreach ($orders as $k => $v) {
                        $temps['order_status'] = 5;// 取消
                        // 更新订单，再写入一条订单历史记录
                        $tempModel = $class::find($v->id);
                        $temp = $temp && $tempModel->update($temps);
                    }
                    if ($temp) {
                        MyUtils::writeLogs('微信支付', '提现充值', 7, '提现取消');
                        return true;
                    } else {
                        MyUtils::writeLogs('微信支付', '提现充值', 7, '提现失败');
                        return false;
                    }
                }
                $temp = DB::transaction(function () use($orders,$class){
                    $temp = true;
                    foreach ($orders as $v){
                        $temps['paid_at'] = DayTimes::getInstance()->now();
                        $temps['order_status'] = 4;// 表示 已付款 代发货
                        $temps['if_payment'] = 1;
                        // 更新订单，再写入一条订单历史记录
                        $tempModel = $class::find($v->id);
                        $temp = $temp && $tempModel->update($temps);
                        if ($temp){
                            return true;
                        }else{
                            DB::rollBack();
                            return false;
                        }
                    }
                });
                if ($temp){
                    MyUtils::writeLogs('微信订单支付','特殊操作',7,'提现成功');
                    return true;
                }else{
                    MyUtils::writeLogs('微信订单支付','特殊操作',7,'提现失败');
                    return false;
                }
                return true; // 返回处理完成
            }catch (\Exception $e){
                MyUtils::writeLogs('微信订单支付','特殊操作',7,json_encode($e));
                return false;
            }
        });
        return $response; // Laravel 里请使用：return $response;
    }
    /**
     * 保存 微信公众端传递来的 发送模板消息的
     * 验证token
     */
    public function saveTemplateToken(){
        $request = $this->request->request->all();
        MyUtils::writeLogs('测试发送模板','测试发送模板$token',99,json_encode($request));
        Redis::set("saveTemplateToken",json_encode($request));
        $data['code'] = 0;
        $data['message'] = "成功";
        $data['data'] = "返回的数据";
        return MyUtils::dealFD($data,1);
    }
}
